package handler

import (
	"2212b/awesomeProject18/api/request"
	"2212b/awesomeProject18/consts"
	"2212b/awesomeProject18/internal/dao"
	"2212b/awesomeProject18/internal/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var req request.RegisterReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile: req.Mobile,
	}, &user)
	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "用户已存在",
			"data": nil,
		})
		return
	}
	IsSuccess := dao.Create(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	})
	if !IsSuccess {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册用户失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": true,
	})
}
func Login(c *gin.Context) {
	var req request.LoginReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	token, err := jwt2.NewJWT(consts.JWT_KEY).CreateToken(jwt2.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().UnixMilli() + 3600*24*1,
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "生成token失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "成功",
		"data": token,
	})
}
